#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int oneRootToLeaf(vector<int>& st)
    {
        int ret = 0;
        for (const auto& i : st)
        {
            ret = 2 * ret + i;
        }
        return ret;
    }
    void _sumRootToLeaf(TreeNode* root, vector<int>& st, vector<int>& v)
    {
        if (root->left == nullptr && root->right == nullptr)
        {
            st.push_back(root->val);
            v.push_back(oneRootToLeaf(st));
            st.pop_back();
            return;
        }

        st.push_back(root->val);
        if (root->left)
            _sumRootToLeaf(root->left, st, v);
        if (root->right)
            _sumRootToLeaf(root->right, st, v);
        st.pop_back();
    }
    int sumRootToLeaf(TreeNode* root) {
        vector<int> st;
        vector<int> v;
        _sumRootToLeaf(root, st, v);
        int sum = 0;
        for (const auto& i : v)
        {
            sum += i;
        }
        return sum;
    }
};